package view;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

import controller.Controller;

import model.Game;
import model.iObservable;
import domain.iObserver;

public class BoardView extends JFrame implements iObserver{
	private static final long serialVersionUID = 1L;

	private JPanel board;
	private Controller controller;
	private JButton[][] fields;

	public BoardView(Controller controller) throws UIException {
		super();
		setController(controller);

		addComponents();
		finalizeLayout(controller.getGame());
	}
	
	private void setController(Controller controller) {
		this.controller = controller;
	}

	private void addComponents() throws UIException {
		board = new JPanel();
		board.setLayout(new GridLayout(controller.getNumberOfRows(), controller.getNumberOfColumns()));
		this.setContentPane(board);

		fields = new JButton[controller.getNumberOfRows()][controller.getNumberOfColumns()];

		for (int row = 0; row < fields.length; row++) {
			for (int column = 0; column < fields[0].length; column++) {
				JButton field = new JButton();
				field.addActionListener(new FieldActionListener());
				fields[row][column] = field	;
				add(field);
			}
		}
	}

	private void finalizeLayout(Game model) {
		this.setTitle(model.getTitel());
		Dimension boardSize = controller.getBoardSize();
		setPreferredSize(boardSize);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		pack();
	}
	
	//Inner class
	private class FieldActionListener implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent e) {
			int rowClicked = -1;
			int columnClicked = -1;
			for (int row = 0; row < fields.length && rowClicked < 0; row++) {
				for (int column = 0; column < fields[0].length && columnClicked < 0; column++) {
					if(fields[row][column] == e.getSource()){
						rowClicked = row;
						columnClicked = column;
					}
				}
			}
			controller.play(rowClicked, columnClicked);
		}
	}
	

	public void redrawBoard() {
		char[][] board = controller.getGame().getBoard().toArray();

		for (int row = 0; row < fields.length; row++) {
			for (int column = 0; column < fields[0].length; column++) {
				String valueAsString = Character.toString(board[row][column]);
				fields[row][column].setText(valueAsString);
				
				if (fields[row][column].getText().equals("X") || 
						fields[row][column].getText().equals("O")){
					fields[row][column].setEnabled(false);
				}
			}
		}
	}

	@Override
	public void update(iObservable subject) {
		redrawBoard();
		this.setTitle(controller.getGame().getTitel());
	}

}
